package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.ItemManager;

import model.User;

/**
 * Servlet implementation class ReturnItemServlet
 */
@WebServlet("/returnItem")
public class ReturnItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ItemManager manager;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.manager = new ItemManager();
	}

	@Override
	public void destroy() {
		this.manager = null;
		super.destroy();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendRedirect("home.jsp");
			return;
		}
		String borrowedItemId = request.getParameter("borrowedItemId");
		if (borrowedItemId != null && !borrowedItemId.equals("")) {
			int borrowedId = Integer.parseInt(borrowedItemId);
			boolean result = false;
			try {
				result = manager.returnItem(borrowedId);
			} catch (SQLException e) {
				System.err.println(e.getMessage());
			}
			String message = "";
			if (result) {
				message = "Item returned successfully.";
			} else {
				message = "There was a problem returning the item.";
			}
			session.setAttribute("message", message);
			response.sendRedirect("items.jsp");
		}
	}

}
